import { Component, Input, Output, EventEmitter, OnInit, OnChanges } from '@angular/core';
import {NzNotificationService, UploadFile} from 'ng-zorro-antd';
import {ActivatedRoute, Router} from '@angular/router';
import { HttpServcie } from '../../../service/http.service';
import { Config } from '../../../service/config';
import { el } from "@angular/platform-browser/testing/src/browser_util";
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { ContractBean } from './../bean/contract.bean';
import {Observable} from 'rxjs/Rx';

@Component({
    selector: 'contract-modify-page',
    templateUrl: 'contract-modify.html',
    styleUrls: ['contract-modify.scss']
})
export class ContractModifyPage implements OnInit, OnChanges {
    validateForm: FormGroup;
    isSpinning: boolean=false;
    functions: any = [];
    data2: any=[];
    partyList: any=[];
    expandDataCache = {};
    @Input() inValue: any = [];
    data=[];
    @Output("outPut") outPut = new EventEmitter()
    //角色信息
    contractBean:ContractBean=new ContractBean();

    //角色添加的权限(功能)
    funList:any=[];

    //甲方
    firstList: any = [];
    //乙方
    secondList: any = [];
    userObject: any;
    firstDisable: boolean = false;
    secondDisable: boolean = false;
    parentId : string;
    config = Config;
    public photoLists :any= [];
  public fileList :any= [];

    constructor(
        private fb: FormBuilder,
        private httpServcie: HttpServcie,
        private _notification: NzNotificationService,
    ) {
        this.validateForm = this.fb.group({
            firstParty: [null, [Validators.required]],
            secondParty: [null, [Validators.required]],
            contractType: [null, []],
        });


      //获取登陆人信息
      let user: string = window.localStorage.getItem("user");
      if (user) {
        this.userObject = JSON.parse(user);
        this.parentId = this.userObject.partyParentId;
      }
      //甲方
      this.queryByIdAndType(this.userObject["partyParentId"], "2");
      //乙方
      this.queryByIdAndType(this.userObject["partyParentId"], "1");

      this.contractBean.partyId = this.userObject.partyId;
    }

    /**
     * 选择checkbox
     * @param event
     * @param param
     */
    refreshStatus(event,param) {
        if(event){
            this.funList.push(param);
        }else{
            //如果非选中状态移除
            if(this.funList.length>0){
                this.httpServcie.removeByValue(this.funList,param);
            }
        }
    }
    ngOnInit() {
    };

    /**
     * 查询甲乙方单位
     * @param partyId
     * @param partyType
     */
    queryByIdAndType(partyId, partyType) {

      let param = {
        partyType: partyType,
        id : this.parentId,
      };
      this.httpServcie.queryByIdAndTypeList(param).subscribe(data => {
        if (data.status == 200) {
          if (partyType == "2") {
            this.firstList = data.data;

            if (this.firstList.length > 0 && this.userObject.partyType == "2") {
              this.contractBean.firstParty = this.userObject.partyId;
              this.firstDisable = true;
            }
          } else if (partyType == "1") {
            this.secondList = data.data;
            if (this.secondList.length > 0 && this.userObject.partyType == "1") {
              this.contractBean.secondParty = this.userObject.partyId;
              this.secondDisable = true;
            }
          }
        }
      });
    }

    //判断是否选中
    executeArray(items) {
        items.map((item) => {
            if (this.funList.includes(item.authorId)) {
                item.checked=true;
            }
            if (item.childList) {
                this.executeArray(item.childList);
            }
        })
    }

    ngOnChanges() {
        this.functions = [];
        if (this.inValue) {
          this.contractBean = Object.assign({}, this.inValue);
          if (this.inValue) {
            //图片回显
            if (this.contractBean.fileList) {
              let list = this.contractBean.fileList.split(",");
              let addList: any = [];

              list.forEach((element, index) => {
                let uid = new Date();
                addList.push({
                  uid: uid.getTime(),
                  name: element,
                  status: "done",
                  url: `${this.config.IP + this.config.API.getUpload}${element}`
                });
              })
              this.fileList = addList;
            }
          };

          this.functions = this.inValue;
        }
        this.data2 = this.data;
    }

    submitForm() {
        //校验是否能提交
        //没有填的标红
        for (const i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
        }
        //处理是否提交
        for (const i in this.validateForm.controls) {
            if(!this.validateForm.controls[i].valid){
                return;
            }
        }
        // 修改照片
      let photo = "";
      if (this.photoLists != null && this.photoLists.length) {
        for (let i = 0; i < this.photoLists.length; i++) {

          if (this.photoLists[i].status == "done") {
            // 回调的图片处理
            if (this.photoLists[i]["url"]) {
              let url = `${this.photoLists[i].name}`;
              photo += url + ",";
            } else {
              let url = `${this.photoLists[i]["response"].data}`;
              photo += url + ",";
            }
            // 上传的图片处理
          }
        }

      }
      this.contractBean.fileList = photo;
        this.isSpinning = true;
        console.log(this.contractBean);

        let ob = this.httpServcie.updateContract(this.contractBean).subscribe(data=>{
            this.isSpinning = false;
            if(data.status==200){
                this._notification.create('success', '成功提示', '修改成功');
                this.outPut.emit(data);
            }else{
                this._notification.create('error', '错误提示', data.message);
            }

        })
    }

    //交验
    getFormControl(name) {
        return this.validateForm.controls[name];
    }


    collapse(array, data, $event) {
        if ($event === false) {
            if (data.childList) {
                data.childList.forEach(d => {
                    const target = array.find(a => a.authorId === d.authorId);
                    target.expand = false;
                    this.collapse(array, target, false);
                });
            } else {
                return;
            }
        }
    }

    convertTreeToList(root) {
        const stack = [], array = [], hashMap = {};
        stack.push({ ...root, level: 0, expand: false });

        while (stack.length !== 0) {
            const node = stack.pop();
            this.visitNode(node, hashMap, array);
            if (node.childList) {
                for (let i = node.childList.length - 1; i >= 0; i--) {
                    stack.push({ ...node.childList[ i ], level: node.level + 1, expand: false, parent: node });
                }
            }
        }

        return array;
    }

    visitNode(node, hashMap, array) {
        if (!hashMap[ node.authorId ]) {
            hashMap[ node.authorId ] = true;
            array.push(node);
        }
    }



  //查看
  //文件上传
  previewImage = "";
  previewVisible = false;
  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  };

 //移除文件
  nzRemoveFile = (file: UploadFile) => {
    let fileItem = file;
    if (fileItem["status"] == "removed") {
      if (fileItem["url"] && fileItem["url"].includes("http")) {
        this.deleteImg(fileItem.name);
      } else {
        this.deleteImg(fileItem["response"]["data"]);
      }
    }
  };

  // 删除图片服务
  deleteImg(filedata) {
    this.httpServcie.deleteUpload(filedata).subscribe(
      data => {
        if (data["status"] != "200") {
          this._notification.create("error", "错误提示", data.message);
          return;
        }
        if(data["status"] == "200"){
          this._notification.create("success", "成功提示", "删除成功，请点击修改按钮，进行数据保存！");
        }else{
          this._notification.create("error", "错误提示", data.message);
        }
        this.fileList.forEach((element, index) => {
          console.log(element);
          if (element["status"] == "removed") {
            this.fileList.splice(index, 1);
            this.photoLists = this.fileList;

            this.fileList = this.photoLists;

          }
        });
      },
      error => {
        this._notification.create("error", "错误提示", "请求超时！");
        return;
      }
    );
  }

  /**
   * 上传就开始调用
   * @param info
   */
  handleChange(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      this.photoLists = this.fileList;
    }
  }


}
